package com.group18.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group18.entity.FamilyUser;
import com.group18.entity.MemberUser;
import com.group18.service.FamilyUserService;
import com.group18.service.MemberUserService;



/**
 * Servlet implementation class DoUpdateFamily
 */
@WebServlet("/DoUpdateFamily")
public class DoUpdateFamily extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoUpdateFamily() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		
		String family_name = request.getParameter("family_name");
		String updateName = request.getParameter("updateName");
		
		//修改家庭名
		FamilyUser fu = new FamilyUser();
		fu.setName(updateName);
		FamilyUserService fus = new FamilyUserService();
		boolean bl =  fus.isExist(fu);
		String msg = "";
		if(!bl) {
			fu.setName(family_name);
			int family_id = fus.selectIDByName(fu);
			fu.setName(updateName);
			fu.setId(family_id);
			int i = fus.upDataFamily(fu);
			
			//修改mamber表对应的家庭信息
			MemberUser mu = new MemberUser();
			mu.setFamily_id(family_id);
			mu.setName(updateName);
			MemberUserService mus = new MemberUserService();
			int j = mus.updateNameByFamily_id(mu);
			if(i > 0) {
				msg = "用户信息修改成功";
			}else {
				msg = "用户信息修改失败";
			}
			
			HttpSession session = request.getSession();
			int id = (int)session.getAttribute("family_id");
			if(family_id == id ) {
				session.setAttribute("name", family_name);
			}
		}else {
			msg = "该家庭已存在";
		}
		request.setAttribute("msg", msg);
		String text = request.getParameter("text");
		if(text != null && !text.equals("")) {
			request.getRequestDispatcher("/DoSearchFamliy").forward(request, response);
		}else {
			request.getRequestDispatcher("/ToFamily").forward(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
